'''
Created on Jul 21, 2011

@author: Krystian Brachmanski
'''

import os
import logging
import shutil

class DirectoryHandler:
    '''
    Class for handling the directory configuration of the tool
    
    @author: Krystian Brachmanski
    
    @requires: os, logging
    '''

    #default values
    documentDir="template/Document.tex"
    directory="./tmp/"
    cpuchartDir="./charts/cpu"
    memchartDir="./charts/mem"
    ioDir="./charts/io"
    reportDir="./report/"
    
    log = logging.getLogger('yapcg.perfparser.dirHandler')
    
    def __init__(self,c):
        '''
        Constructor
        @param c: ConfigParser object providing the configuration details 
        '''
        self.directory =  self.reportDir + c.get('config','outdatadir')
        chartDir = c.get('config','outchartdir')
        self.cpuchartDir = chartDir + "cpu/"
        self.memchartDir = chartDir + "mem/"
        self.iochartDir = chartDir + "io/"
        self.document = c.get('config','documentTemplate')

    # might be subject to hazard if multiple instance work on the same working dir
    def ensureDirectory(self,dir):
        '''
        Check if directory exists - if not creates one
        @param dir: directory to be checked as string 
        '''        
        if not os.path.exists(dir):
            self.log.debug("Directory does not exists - creating directory : " + dir)
            os.makedirs(dir)

    def verifyDirectoryStricture(self):
        '''
        Verify if directory structure is ok
        ''' 
        for i in [self.directory, self.reportDir + self.cpuchartDir, self.reportDir + self.memchartDir, self.reportDir + self.iochartDir]:
            self.ensureDirectory(i)
        self.log.info("Copying template: " + self.document + " to: " + self.reportDir)
        shutil.copy(self.document, self.reportDir)
        return        

    def getIoChartFilepath(self,filename):
        '''
        @return: the path to the io charts
        '''
        return self.iochartDir + "/" + filename
    
    def getMemChartFilepath(self,filename):
        '''
        @return: the path to the memory charts
        '''
        return self.memchartDir + "/" + filename
    
    def getCpuChartFilepath(self,filename):
        '''
        @return: the path to the cpu charts
        '''
        return self.cpuchartDir + "/" + filename
   
    def getDirectoryForGnuplotFile(self,name):
        '''
        @return: the path to the gnuplot configuration files
        '''
        return self.directory + "/" + name

    def getDataFileName(self, name):
        '''
        @return: the path to the data files
        '''
        if not name.endswith("data"):
            name += ".data"
        return self.directory + "/" + name    

    @property
    def documentFile(self):
        return os.path.basename(self.document)

    @property
    def documentPath(self):
        return os.path.dirname(self.document)
